<?php

namespace Biz\service\activity;

use Biz\cache\activity\WeekPurchase as cWeekPurchase;
use Biz\model\activity\ActivityRegisterGoods as mActivityRegisterGoods;
use Biz\model\activity\ActivityRegisterInfo as mActivityRegisterInfo;
use Biz\model\activity\ActivityRegisterShop as mActivityRegisterShop;
use Biz\model\activity\AllActivityGoods as mAllActivityGoods;
use Biz\model\activity\AllActivitySku as mAllActivitySku;
use Biz\model\activity\ShopGreyList as mShopGreyList;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\SelectGoodsLog as mSelectGoodsLog;
use Biz\model\ShopBasicInfo as mShopBasicInfo;
use Biz\model\ShopFavorite as mShopFavorite;
use Biz\model\ShopSpecial as mShopSpecial;
use Biz\model\ShopSpecialGoods as mShopSpecialGoods;
use Biz\model\ShopSpecialTempl as mShopSpecialTempl;
use Biz\model\trade\Cart as mCart;
use Biz\model\trade\CartV as mCartV;
use Biz\model\trade\OrderGoods as mOrderGoods;
use Biz\module\Classes\adm\RegisterExcel as admRegisterExcel;
use Biz\module\Classes\mgt\ActiviesRegisterSave;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\service\activity\AllActivityInfo as sAllActivityInfo;
use Biz\service\esSearch\Goods as esGoods;
use Biz\service\Goods as sGoods;
use Biz\service\SearchGoods;
use Biz\service\ShopInfo as sShopInfo;
use Biz\service\ShopSpecial as sShopSpecial;
use Biz\service\Sku as sSku;
use Biz\tools\BizUrl as tBizUrl;
use Doraemon\model\Category as mCategory;
use Doraemon\model\Member;
use Doraemon\service\search\AdmUserSearch;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log as tLog;
use Medoo\Medoo;

class ActivityRegisterInfo
{

    const TABTYPE_NORMAL = 1; // 进行中活动
    const TABTYPE_OVER = 2; // 已关闭

    /**
     * 管理后台 报名活动列表
     * @param $page
     * @param int $pageSize
     * @return array
     */
    public static function admGetRegisterList($page, $pageSize = 20)
    {
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = [
            'status' => [mActivityRegisterInfo::STATUS_NORMAL, mActivityRegisterInfo::STATUS_CLOSE]
        ];
        $order = ['status' => 'DESC', 'stop_time' => 'DESC'];
        $infos = mActivityRegisterInfo::getRegisterInfos($where, $limit, $order);
        $count = mActivityRegisterInfo::getRegisterInfosCount($where);

        $list = [];
        if ($infos) {
            $registerIds = array_keys($infos);

            // 计算已经选中的商品数量
            $selectGoodsLog = mSelectGoodsLog::select(['register_id', 'goods_id'], [
                'AND' => [
                    'register_id' => $registerIds,
                    'status' => mSelectGoodsLog::STATUS_NORMAL,
                    'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
                ]
            ]);
            $selectGoodsCountAll = [];
            foreach ($selectGoodsLog as $goodsLog) {
                $selectGoodsCountAll[$goodsLog['register_id']][] = $goodsLog['goods_id'];
            }

            $registerGoodsList = mActivityRegisterGoods::select(['register_id', 'count' => Medoo::raw("count(distinct `goods_id`)")], [
                'AND' => [
                    'register_id' => $registerIds,
                    'status' => mActivityRegisterGoods::STATUS_NORMAL,
                ],
                'GROUP' => ['register_id']
            ]);

            $registerGoodsList = array_column($registerGoodsList, null, 'register_id');

            $registerGoods = [];//已报名商品数量
            $registerGoodsSelected = [];//已选中商品数量
            foreach ($registerGoodsList as $row) {
                $registerGoods[$row['register_id']] = $row['count'];
                $registerGoodsSelected[$row['register_id']] = 0;
                if (isset($selectGoodsCountAll[$row['register_id']])) {
                    $registerGoodsSelected[$row['register_id']] = count(array_unique($selectGoodsCountAll[$row['register_id']]));
                }
            }

            foreach ($infos as $registerId => $info) {
                $info['goods_count'] = isset($registerGoods[$registerId]) ? $registerGoods[$registerId] : 0;
                $info['goods_selected_count'] = isset($registerGoodsSelected[$registerId]) ? $registerGoodsSelected[$registerId] : 0;
                $list[] = $info;
            }
        }
        return ['list' => $list, 'count' => $count];
    }

    /**
     * 管理后台 更改报名活动状态
     * @param $registerId 活动id
     * @param $status 状态
     * @return bool
     * @throws \Exception
     */
    public static function admChangeRegisterStatus($registerId, $status)
    {
        $data = ['status' => $status];
        $where = ['id' => $registerId];
        $res = mActivityRegisterInfo::updateData($data, $where);
        return $res;
    }

    /**
     * 管理后台新加或则编辑报名活动信息
     * @param $data
     * @param int $registerId
     * @return bool
     * @throws
     */
    public static function admEditRegisterInfo($data, $registerId = 0)
    {
        $isAllShop = $data['all_shop'];
        if ($data['num'] < 2) {
            throw new \Exception('限报数量应该大于2');
        }
        if (!$registerId) {//新加报名
            $insertInfoData = [
                'up_files' => $data['up_files'],
                'title' => $data['title'],
                'desc' => $data['desc'],
                'required' => $data['required'],
                'all_shop' => $data['all_shop'],
                'num' => $data['num'],
                'stop_time' => $data['stop_time'],
                'status' => mActivityRegisterInfo::STATUS_NORMAL,
            ];
            $result = mActivityRegisterInfo::action(function () use ($insertInfoData, $data, $isAllShop) {
                $registerId = mActivityRegisterInfo::insertData($insertInfoData);
                if ($registerId) {
                    $shopIds = [];
                    if ($isAllShop == mActivityRegisterInfo::ALL_SHOP_NO) {
                        $shopIds = $data['shop_ids'] ? explode(',', $data['shop_ids']) : [];
                    } else if ($isAllShop == mActivityRegisterInfo::ALL_SHOP_GREY_LIST) {
                        // 一键排除灰名单商家
                        $shopIds = mShopBasicInfo::select('shop_id', ['status' => mShopBasicInfo::STATUS_OPENED]);
                        $greyShopIds = mShopGreyList::select('shop_id', ['status' => mShopGreyList::STATUS_NORMAL]);
                        $shopIds = array_diff($shopIds, $greyShopIds); // 排除活动灰名单商家
                    }

                    if ($shopIds) {
                        foreach ($shopIds as $shopId) {
                            $insertShopData = [
                                'register_id' => $registerId,
                                'shop_id' => $shopId,
                                'status' => mActivityRegisterShop::STATUS_NORMAL
                            ];
                            $id = mActivityRegisterShop::insertData($insertShopData);
                            if (!$id) {
                                throw new \Exception('添加报名活动商家失败');
                            }
                        }
                    }

                } else {
                    throw new \Exception('添加报名活动基础信息失败');
                }
                return true;
            });
        } else {//编辑报名信息
            $registerInfo = mActivityRegisterInfo::getRegisterInfo($registerId);
            if ($data['num'] < $registerInfo['num']) {
                throw new \Exception('限报数量只能改大不能改小');
            }
            $allShopIds = [];
            $shopIds = [];
            $normalShopIds = [];
            if ($isAllShop == mActivityRegisterInfo::ALL_SHOP_NO || $isAllShop == mActivityRegisterInfo::ALL_SHOP_GREY_LIST) {
                if ($registerInfo['all_shop'] == mActivityRegisterInfo::ALL_SHOP_YES) {
                    throw new \Exception('指定商家只能改大不能改小');
                }
                if ($isAllShop == mActivityRegisterInfo::ALL_SHOP_NO) {
                    $shopIds = $data['shop_ids'] ? explode(',', $data['shop_ids']) : [];
                }
                if ($isAllShop == mActivityRegisterInfo::ALL_SHOP_GREY_LIST) {
                    // 排除灰名单商家
                    $shopIds = mShopBasicInfo::select('shop_id', ['status' => mShopBasicInfo::STATUS_OPENED]);
                    $greyShopIds = mShopGreyList::select('shop_id', ['status' => mShopGreyList::STATUS_NORMAL]);
                    $shopIds = array_diff($shopIds, $greyShopIds); // 排除活动灰名单商家
                }

                $shopList = mActivityRegisterShop::getList(['register_id' => $registerId], '*');
                foreach ($shopList as $row) {
                    array_push($allShopIds, $row['shop_id']);
                    if ($row['status'] == mActivityRegisterShop::STATUS_NORMAL) {
                        array_push($normalShopIds, $row['shop_id']);
                    }
                }
                if ($normalShopIds && array_diff($normalShopIds, $shopIds) && $isAllShop == mActivityRegisterInfo::ALL_SHOP_NO) {//店铺只能增加不能减少
                    throw new \Exception('指定商家只能改大不能改小');
                }
            }
            $result = mActivityRegisterInfo::action(function () use ($registerId, $data, $isAllShop, $shopIds, $allShopIds) {
                $updateInfoData = [
                    'up_files' => $data['up_files'],
                    'title' => $data['title'],
                    'desc' => $data['desc'],
                    'required' => $data['required'],
                    'all_shop' => $data['all_shop'],
                    'num' => $data['num'],
                    'stop_time' => $data['stop_time'],
                ];
                $result = mActivityRegisterInfo::updateData($updateInfoData, ['id' => $registerId]);
                if ($result) {
                    if ($isAllShop == mActivityRegisterInfo::ALL_SHOP_NO || $isAllShop == mActivityRegisterInfo::ALL_SHOP_GREY_LIST) { //指定商家或者排除灰名单商家
                        foreach ($shopIds as $shopId) {
                            if (in_array($shopId, $allShopIds)) {
                                $updateShopData = [
                                    'status' => mActivityRegisterShop::STATUS_NORMAL
                                ];
                                $result = mActivityRegisterShop::updateData($updateShopData, ['register_id' => $registerId, 'shop_id' => $shopId]);
                                if (!$result) {
                                    throw new \Exception('修改报名活动商家失败');
                                }
                            } else {
                                $insertShopData = [
                                    'register_id' => $registerId,
                                    'shop_id' => $shopId,
                                    'status' => mActivityRegisterShop::STATUS_NORMAL
                                ];
                                $result = mActivityRegisterShop::insertData($insertShopData);
                                if (!$result) {
                                    throw new \Exception('修改报名活动商家失败');
                                }
                            }
                        }
                    } else {//全部商家
                        $result = mActivityRegisterShop::updateData(['status' => mActivityRegisterShop::STATUS_DELETE], ['register_id' => $registerId]);
                        if (!$result) {
                            throw new \Exception('修改报名活动商家失败');
                        }
                    }
                } else {
                    throw new \Exception('修改报名活动基础信息失败');
                }
                return $result;
            });
        }
        return $result;
    }

    /**
     * 获取预览链接
     * @param $goodsInfo
     * @return mixed
     */
    private static function getPreviewUrl($goodsInfo)
    {
        foreach ($goodsInfo as $info) {
            $goodsInfo[$info['goods_id']]['goods_h5_url'] = tBizUrl::h5GoodsInfo($info['goods_id']);
        }

        return $goodsInfo;
    }

    /**
     * 选择商品列表页
     * @param $registerId
     * @param $param
     * @param $page
     * @param $pageSize
     * @return array
     */
    public static function admGetRegisterGoods($registerId, $param, $page, $pageSize)
    {
        $where = self::buildWhere($registerId, $param);

        $registerInfo = mActivityRegisterInfo::getRegisterInfoByRegisterId($registerId);
        $registerInfo['is_end'] = strtotime($registerInfo['stop_time']) < time() ? 1 : 0;
        $goodsList = mActivityRegisterGoods::getRegisterGoods($where, ['register_id', 'discount_level', 'discount_type', 'goods_id', 'sku_id', 'is_pick_up', 'discount_degree', 'status(is_check)', 'actual_price']);
        $goodsIds = array_unique(array_column($goodsList, 'goods_id'));
        $goodsCount = count($goodsIds) ?: 0;
        if (!is_null($page)) $goodsIds = array_slice($goodsIds, ($page - 1) * $pageSize, $pageSize);

        $goodsInfo = sGoods::goods($goodsIds, sGoods::FIELDS_GROUP_ADMIN); // 商品的基础信息
        $goodsInfo = self::getShopInfoByGoodsInfo($goodsInfo); // 获取商家信息
        $goodsInfo = self::getCartTotalByGoodsIds($goodsIds, $goodsInfo); // 商品的加购信息
        $goodsInfo = self::getFavTotalByGoodIds($goodsIds, $goodsInfo); // 商品的收藏信息
        $goodsInfo = self::formatPrice($goodsIds, $goodsList, $goodsInfo); // 计算折扣
        $goodsInfo = self::getCateGoryName($goodsInfo); // 获取分类名称
        $goodsInfo = self::getPreviewUrl($goodsInfo); // 获取预览链接
        $goodsInfo = self::getRecentActivity($goodsIds, $goodsInfo); // 最近一场活动
        $goodsInfo = self::getSelectedActivityTitle($registerId, $goodsInfo); // 获取选中的活动标题


        $registerInfo['goods_info'] = array_values($goodsInfo);

        return ['list' => $registerInfo, 'count' => $goodsCount];
    }

    /**
     * 获取选中的活动标题
     * @param $registerId
     * @param $goodsInfo
     * @return mixed
     */
    private static function getSelectedActivityTitle($registerId, $goodsInfo)
    {
        $activityTitle = [];
        $selectGoodsLog = mSelectGoodsLog::select('*', [
            'register_id' => $registerId,
            'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE,
            'status' => mSelectGoodsLog::STATUS_NORMAL
        ]);
        $activityId = array_unique(array_column($selectGoodsLog, 'activity_id'));
        $activityInfo = mShopSpecial::select('*', ['id' => $activityId]);
        $activityInfo = empty($activityInfo) ? [] : array_column($activityInfo, null, 'id');

        foreach ($selectGoodsLog as $goods) {
            if (isset($activityInfo[$goods['activity_id']])) {
                if (!isset($activityTitle[$goods['goods_id']])) {
                    $activityTitle[$goods['goods_id']][] = $activityInfo[$goods['activity_id']]['special_title'];
                } else {
                    if (!in_array($activityInfo[$goods['activity_id']]['special_title'], $activityTitle[$goods['goods_id']])) {
                        $activityTitle[$goods['goods_id']][] = $activityInfo[$goods['activity_id']]['special_title'];
                    }
                }

            }
        }

        foreach ($goodsInfo as $goodsId => $info) {
            $goodsInfo[$goodsId]['special_title_list'] = isset($activityTitle[$goodsId]) ? $activityTitle[$goodsId] : [];
        }

        return $goodsInfo;
    }

    /**
     * 获取最近参加的一场活动
     * @param $goodsIds
     * @param $goodsInfo
     * @return mixed
     */
    private static function getRecentActivity($goodsIds, $goodsInfo)
    {
        if ($goodsIds) {
            $recentTitle = cWeekPurchase::getWeekPurchase($goodsIds);
            foreach ($recentTitle as $goodsId => $info) {
                if (isset($goodsInfo[$goodsId])) {
                    $goodsInfo[$goodsId]['recent_special_title'] = $info['title'];
                }
            }
        }
        return $goodsInfo;
    }

    /**
     * 获取入选的活动
     * @param $registerId
     * @return array
     */
    public static function getCheckSpecial($registerId)
    {
        $checkSpecial = [];
        $list = mSelectGoodsLog::select('activity_id', [
            'register_id' => $registerId,
            'status' => mSelectGoodsLog::STATUS_NORMAL,
            'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
        ]);
        $activityId = array_unique($list);
        $specialInfo = mShopSpecial::getInfosBySpcialIdsAndType($activityId, mShopSpecial::TYPE_SPECIAL_REGISTER, null, ['id', 'special_title']);
        $specialInfo = empty($specialInfo) ? [] : $specialInfo;
        // 入选的活动
        foreach ($specialInfo as $value) {
            $checkSpecial[$value['id']] = $value['special_title'];
        }
        return $checkSpecial ?: [];
    }

    /**
     * 管理后台 获取报名活动信息
     * @param $registerId
     * @return array
     */
    public static function admGetRegisterInfo($registerId)
    {
        $info = mActivityRegisterInfo::getRegisterInfo($registerId);
        if ($info) {
            if (!$info['all_shop']) {
                $shops = mActivityRegisterShop::getShops($registerId);
                $shopIds = $shops ? array_column($shops, 'shop_id') : [];
                $info['shops'] = [];
                if ($shopIds) {
                    $shopList = mShopBasicInfo::getInfoList($shopIds);
                    $info['shop_ids'] = array_keys($shopList);
                    $info['shops'] = array_values($shopList);
                }
            }
        }
        return $info;
    }

    /**
     * 将选中的商品添加至活动附属表和活动价格表
     * @param $registerId
     * @param $activityId
     * @param $goodsIds
     * @param $adminId
     * @return array|bool
     */
    public static function admAddActivity($registerId, $activityId, $goodsIds, $adminId)
    {
        $specialInfo = mShopSpecial::getSpecialInfoById($activityId, mShopSpecial::TYPE_SPECIAL_REGISTER, ['id', 'start_time', 'end_time', 'special_title']);
        $filterGoodsId = mShopSpecialGoods::getList(['status' => mShopSpecialGoods::STATUS_PASSED, 'special_id' => $activityId], 'goods_id');
        $goodsIds = array_diff($goodsIds, $filterGoodsId);
        if (!$goodsIds) return false; // 因为选品页面的选中无法屏蔽商品已选的活动，所以需要过滤掉添加过的商品
        $goodsIdsCount = count($goodsIds);

        // 验证时间
        list($goodsIds, $invalidTimeData) = AllactivityInfoBak::admCheckActivityTime($goodsIds, $specialInfo, AllactivityInfoBak::ACTIVITY_TYPE_WEEK_PURCHASE, $activityId);
        if ($goodsIdsCount == 1 && $invalidTimeData) {
            return ['code' => 1, 'msg' => '商品已入选了活动 ' . reset($invalidTimeData)['activity_id'] . ' 与本活动的时间重叠，不能加入'];
        }

        // 验证价格
        $checkGoodsList = [];
        $goodsList = mActivityRegisterGoods::getRegisterGoods(['register_id' => $registerId, 'goods_id' => $goodsIds, 'status' => mActivityRegisterGoods::STATUS_NORMAL], ['register_id', 'goods_id', 'sku_id', 'discount_degree', 'actual_price']);
        foreach ($goodsList as $info) {
            $checkGoodsList[$info['goods_id']][$info['sku_id']] = $info['actual_price'];
        }

        list($goodsIds, $invalidPriceData) = AllactivityInfoBak::admCheckActivityPrice($checkGoodsList, $specialInfo, AllactivityInfoBak::ACTIVITY_TYPE_WEEK_PURCHASE);
        if ($goodsIdsCount == 1 && $invalidPriceData) {
            return ['code' => 1, 'msg' => '该商品的 ' . reset($invalidPriceData)['type'] . ' 价高于同时间段的商家直降价，请修改' . reset($invalidPriceData)['type'] . '价格或时间后再选中'];
        }

        $result = true;
        if (!empty($goodsIds)) {
            $goodsInfo = mGoodsBasicInfo::getInfoList($goodsIds);
            $activityGoodsInfo = self::buildActivityGoods($activityId, $goodsIds, $specialInfo, $goodsInfo);
            $activitySkuInfo = self::buildActivitySku($activityId, $goodsIds, $specialInfo, $goodsInfo, $goodsList);

            $logList = self::buildSelectGoodsLogData($registerId, $activityId, $goodsIds, $goodsInfo, $adminId, $goodsList, $specialInfo);
            $result = mSelectGoodsLog::action(function () use ($activityId, $registerId, $goodsIds, $activityGoodsInfo, $activitySkuInfo, $logList, $specialInfo) {
                $result = self::insertSpecial($goodsIds, $activityId);
                if (!$result) {
                    return false;
                }

                $result = mSelectGoodsLog::insertLog($logList);
                if (!$result) {
                    return false;
                }

                //同步活动总表
                $activityInfoResult = sAllActivityInfo::admUpdateActivityInfo($activityId, ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE, $activityGoodsInfo, $activitySkuInfo, ActivityInfo::ALL_ACTIVITY_TYPE_WEEK_PURCHASE, false);
                if ($activityInfoResult == false) {
                    return false;
                }

                return true;
            });

        }

        if ($goodsIdsCount != 1 && $invalidTimeData) {
            return ['code' => 2, 'msg' => '部分商品因活动时间冲突，未能加入活动，请单独选中'];
        }
        if ($goodsIdsCount != 1 && $invalidPriceData) {
            return ['code' => 2, 'msg' => '部分商品加入活动失败，请稍后单独选中'];
        }

        // 设置最近一场活动
        if ($result) {
            $result = self::setRecentActivity($goodsIds, $specialInfo);
        }

        return $result;
    }

    /**
     * 设置最近一场活动
     * @param $goodsIds
     * @param $specialInfo
     * @return bool
     */
    private static function setRecentActivity($goodsIds, $specialInfo)
    {
        // 最近一场活动的规则是 活动必须为进行中或者已结束 且开始时间最大的一场活动
        $items = [];
        foreach ($goodsIds as $goodsId) {
            $items[$goodsId] = [
                'goods_id' => $goodsId,
                'activity_id' => $specialInfo['id'],
                'title' => $specialInfo['special_title'],
                'start_time' => $specialInfo['start_time'],
                'end_time' => $specialInfo['end_time'],
            ];
        }

        // 获取商品的最近一场活动的信息
        $recentTitleList = cWeekPurchase::getWeekPurchase($goodsIds);

        if ($recentTitleList) {
            // 比对时间
            foreach ($goodsIds as $goodsId) {
                if (isset($recentTitleList[$goodsId]) && $items[$goodsId]['start_time'] < $recentTitleList[$goodsId]['start_time']) {
                    unset($items[$goodsId]);
                }
            }
        }

        // 存储信息
        if ($items) {
            $result = cWeekPurchase::setWeekPurchase($items);
            if (!$result) {
                return false;
            }
        }

        return true;
    }

    /**
     * 同步至special相关表
     * @param $goodsIds
     * @param $activityId
     * @return bool
     */
    private static function insertSpecial($goodsIds, $activityId)
    {
        foreach ($goodsIds as $goodsId) {
            $list = [
                'special_id' => $activityId,
                'special_type' => mShopSpecialTempl::SPECIAL_ACTIVITY,
            ];
            $result = mShopSpecialTempl::insert($list)->rowCount();
            if ($result) {
                $tempId = mShopSpecialTempl::id();
                $list['templ_id'] = $tempId;
                $list['goods_id'] = $goodsId;
                $result = mShopSpecialGoods::insert($list)->rowCount();
                if (!$result) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * 取消选中商品
     * @param $specialId
     * @param $goodsIds
     * @param $registerId
     * @return mixed
     */
    public static function uncheckGoods($specialId, $goodsIds, $registerId)
    {

        $result = mActivityRegisterGoods::action(function () use ($specialId, $registerId, $goodsIds) {
            $result = mActivityRegisterGoods::changeStatusRegisterGoods($registerId, $goodsIds);
            if (!$result) {
                return false;
            }

            $result = sAllActivityInfo::admDelActivityByGoodsId($specialId, ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE, $goodsIds, ActivityInfo::ALL_ACTIVITY_TYPE_WEEK_PURCHASE);
            if (!$result) {
                return false;
            }

            return true;
        });

        return $result;
    }

    /**
     * 商家后台 报名活动列表
     * @param $shopId
     * @param $tabType  过期 或 进行中
     * @param $page
     * @param int $pageSize
     * @return array
     * @author  cailusen
     */
    public static function mgtRegisterList($shopId, $tabType, $page, $pageSize = 20)
    {
        $registerIds = mActivityRegisterShop::getRegsterIdsByShopId($shopId);
        $where = [];
        if ($registerIds) $where['OR']['id'] = $registerIds; //参加报名的活动
        $where['OR']['all_shop'] = mActivityRegisterInfo::ALL_SHOP_YES; // 包括全部的
        $where = array_merge($where,
            $tabType == self::TABTYPE_NORMAL ?
                ['status' => mActivityRegisterInfo::STATUS_NORMAL]
                :
                ['status' => mActivityRegisterInfo::STATUS_CLOSE] //过期和手动关闭
        );
        $infos = mActivityRegisterInfo::getRegisterInfos($where, [($page - 1) * $pageSize, $pageSize], ['stop_time' => 'DESC']);
        $registerId = array_column($infos, 'id');
        $registerGoods = mActivityRegisterGoods::getInfos($registerId, $shopId, false, ['register_id', 'goods_id']);
        $allGoodsIds = [];
        foreach ($registerGoods as $goods) {
            $allGoodsIds[$goods['register_id']][] = $goods['goods_id'];
        }
        $selectGoodsLog = mSelectGoodsLog::select(['register_id', 'goods_id'], [
            'register_id' => $registerId,
            'shop_id' => $shopId,
            'status' => mSelectGoodsLog::STATUS_NORMAL,
            'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
        ]);
        $selectedGoodsIds = [];
        foreach ($selectGoodsLog as $goods) {
            $selectedGoodsIds[$goods['register_id']][] = $goods['goods_id'];
        }

        $count = mActivityRegisterInfo::count($where);
        $results = ['total' => $count, 'list' => []];
        foreach ($infos as $info) {
            $data = [
                'id' => $info['id'],
                'title' => $info['title'],
                'desc' => $info['desc'],
                'required' => $info['required'] . "; 每位商家最多提报" . $info['num'] . "件商品",
                'stop_time' => $info['stop_time'],
                'num' => $info['num'],
                'status' => $info['status'],
                'status_des' => mActivityRegisterInfo::STATUS_DESC[$info['status']],
                'register_num' => isset($allGoodsIds[$info['id']]) ? count(array_unique($allGoodsIds[$info['id']])) : 0,
                'selected_num' => isset($selectedGoodsIds[$info['id']]) ? count(array_unique($selectedGoodsIds[$info['id']])) : 0
            ];
            if ($info['status'] == mActivityRegisterInfo::STATUS_NORMAL) {
                $results['list'][] = $data;
            } else if ($info['status'] == mActivityRegisterInfo::STATUS_CLOSE && $data['register_num']) {
                $results['list'][] = $data;
            }
        }

        return $results;
    }

    /**
     * 报名信息
     * @param $registerId
     * @param $shopId
     * @return array
     * @throws \Exception
     * @author  cailusen
     */
    public static function mgtRegisterInfo($registerId, $shopId)
    {
        if (!self::isExist($registerId, $shopId)) {
            throw new \Exception('不存在此类活动');
        }
        $registerInfo = mActivityRegisterInfo::getRegisterInfo($registerId);
        $goodsList = mActivityRegisterGoods::getInfos([$registerId], $shopId)[$registerId];

        // 查询日志表 查看是否已选中
        $selectGoodsLog = mSelectGoodsLog::select('goods_id', [
            'register_id' => $registerId,
            'shop_id' => $shopId,
            'status' => mSelectGoodsLog::STATUS_NORMAL,
            'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
        ]);
        $selectedGoodsIds = array_flip($selectGoodsLog);

        $goodsIds = $goodsList ? array_keys($goodsList['goods']) : [];
        foreach ($goodsIds as $goodsId) {
            if (isset($selectedGoodsIds[$goodsId])) {
                $goodsList['goods'][$goodsId]['is_selected'] = 1;
            }
        }

        $goodsInfos = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_BASE);
        $selectedInfos = sShopSpecial::getRegisterSpecialInfos($goodsIds, true, mShopSpecialGoods::TYPE_SPECIAL_REGISTER, $registerId);
        if ($goodsList) foreach ($goodsList['goods'] as $goodsId => $goods) {
            $skuIds = array_column($goods['skus'], 'sku_id');
            $skuInfos[$goodsId] = sSku::Sku4Order($skuIds);
        }
        // 反算 discount_degree
        $discountDegree = self::backCalDiscountDegree($goodsList['discount_type'], $goodsList, $skuInfos);
        $up_files = explode(',', $registerInfo['up_files']);
        foreach ($up_files as $key => $v) {
            $up_files[$key] = [
                'name' => '提报说明' . ($key + 1),
                'uri' => $v,
            ];
        }

        $results = [
            'id' => $registerInfo['id'],
            'title' => $registerInfo['title'],
            'desc' => $registerInfo['desc'],
            'required' => $registerInfo['required'] . "; 每位商家最多提报" . $registerInfo['num'] . "件商品",
            'stop_time' => $registerInfo['stop_time'],
            'up_files' => $up_files,
            'discount_level' => ($goodsList) ? $goodsList['discount_level'] : (string)1,
            'num' => $registerInfo['num'],
            'discount_type' => $goodsList ? $goodsList['discount_type'] : (string)1,
            'status' => $registerInfo['status'],
            'status_des' => mActivityRegisterInfo::STATUS_DESC[$registerInfo['status']],
            'goods' => []
        ];
        foreach ($goodsInfos as $goodsId => $goodsInfo) {
            $skus = [];
            foreach ($skuInfos[$goodsId] as $skuInfo) {
                $skus[] = [
                    'sku_id' => $skuInfo['sku_id'],
                    'name' => $skuInfo['sku_desc'],
                    'price' => $skuInfo['ori_price'],
                    'discount_degree' => isset($discountDegree[$skuInfo['sku_id']]) ? $discountDegree[$skuInfo['sku_id']] : '',
                    'activity_price' => $goodsList['goods'][$goodsInfo['goods_id']]['skus'][$skuInfo['sku_id']]['actual_price'],
                    'stock' => $skuInfo['actual_stock'],
                ];
            }
            $results['goods'][] = [
                'goods_id' => $goodsInfo['goods_id'],
                'title' => $goodsInfo['title'],
                'stock' => $goodsInfo['stock'],
                'discount_degree' => isset($discountDegree[$skuInfo['sku_id']]) ? $discountDegree[$skuInfo['sku_id']] : '',
                'min_price' => min(array_column($skus, 'price')),
                'max_price' => max(array_column($skus, 'price')),
                'activity_min_price' => min(array_column($goodsList['goods'][$goodsInfo['goods_id']]['skus'], 'actual_price')),
                'activity_max_price' => max(array_column($goodsList['goods'][$goodsInfo['goods_id']]['skus'], 'actual_price')),
                'spec_img_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $goodsInfo['spec_img'], ImgUrl::IMAGE_SIZE_ORI_NPHONE),
                'is_selected' => $goodsList['goods'][$goodsInfo['goods_id']]['is_selected'] ?: 0,
                'activity_register_tags' => isset($selectedInfos[$goodsInfo['goods_id']]) ? array_column($selectedInfos[$goodsInfo['goods_id']], 'special_title') : [],
                'is_pick_up' => $goodsList['goods'][$goodsInfo['goods_id']]['is_pick_up'],
                'skus' => $skus
            ];

        }

        return $results;
    }

    private static function backCalDiscountDegree($discountType, $goodsList, $skuInfos)
    {
        $results = [];
        if ($goodsList && $goodsList['goods']) foreach ($goodsList['goods'] as $goodsid => $goods) {
            foreach ($goods['skus'] as $skuId => $skus) {
                $oriPrice = $skuInfos[$goodsid][$skuId]['ori_price'];
                switch ($discountType) {
                    case mActivityRegisterGoods::DISCOUNT_TYPE_DEFAULT:
                        $results[$skuId] = round($skus['actual_price'] / $oriPrice * 10, 1);
                        break;
                    case mActivityRegisterGoods::DISCOUNT_TYPE_REDUCE_MONEY:
                        $results[$skuId] = round($oriPrice - $skus['actual_price'], 2);
                        break;
                    case mActivityRegisterGoods::DISCOUNT_TYPE_PROMOTION:
                        $results[$skuId] = $skus['actual_price'];
                        break;
                    default:
                        throw new \Exception('数据库数据错误');
                }
            }
        }
        return $results;
    }

    /**
     * 商品参加报名活动
     * @param $registerId
     * @param $shopId
     * @param $discountLevel
     * @param $discountType
     * @param array $goodsList
     * @throws \Exception
     */
    public static function mgtPostRegister($registerId, $shopId, $discountLevel, $discountType, array $goodsList)
    {
        try {
            tLog::debug('商家保存报名信息shop_id:' . $shopId . "registerId:" . $registerId, [
                'register_id' => $registerId,
                'shop_id' => $shopId,
                'discount_level' => $discountLevel,
                'discount_type' => $discountType,
                'goods_list' => $goodsList,
            ]);

            //活动是否存在
            $isExist = self::isExist($registerId, $shopId);
            if (!$isExist) throw new \Exception('报名活动已关闭或不存在');
            if (!(isset(mActivityRegisterGoods::DISCOUNT_TYPE_DESC[$discountType]) && isset(mActivityRegisterGoods::DISCOUNT_LEVEL_DESC[$discountLevel]))) throw new \Exception('优惠级别 优惠方式不许为空');

            (new ActiviesRegisterSave())->save($registerId, $shopId, $discountType, $discountLevel, $goodsList);

        } catch (\Exception $e) {
            tLog::warning('商家保存活动报名信息出错shop_id:' . $shopId . "registerId:" . $registerId, [
                'e_msg' => $e->getMessage(),
                'e_file' => $e->getFile(),
                'e_line' => $e->getLine(),
                'args' => array_combine([
                    'registerId',
                    'shopId',
                    'discountLevel',
                    'discountType',
                    'goodsList'
                ], func_get_args())
            ]);
            throw $e;
        }

    }

    /**
     * 商家后台获取报名活动通知消息和入选活动通知消息
     * @param $shopId
     * @return  array
     */
    public static function mgtGetRegisterNotifyForShop($shopId)
    {
        $result = [
            'activity_register_info' => [],
            'activity_register_goods' => []
        ];

        //报名活动通知
        $registerInfoList = mActivityRegisterInfo::getRegisterInfos(['status' => mActivityRegisterInfo::STATUS_NORMAL]);
        if ($registerInfoList) {
            $registerIds = [];
            $someRegisterIds = [];
            foreach ($registerInfoList as $registerId => $registerInfo) {
                if ($registerInfo['all_shop'] == mActivityRegisterInfo::ALL_SHOP_YES) {
                    array_push($registerIds, (string)$registerId);
                } else {
                    array_push($someRegisterIds, (string)$registerId);
                }
            }
            if ($someRegisterIds) {
                $registerShopList = mActivityRegisterShop::getList(['register_id' => $someRegisterIds, 'status' => mActivityRegisterShop::STATUS_NORMAL, 'shop_id' => $shopId], ['register_id']);
                $someRegisterIds = array_column($registerShopList, 'register_id');
            }
            $registerIds = array_merge($registerIds, $someRegisterIds);

            $where = [
                'status' => [mSelectGoodsLog::STATUS_NORMAL],
                'shop_id' => $shopId,
                'register_id' => $registerIds,
                'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
            ];
            $goodsList = mSelectGoodsLog::select(['register_id', 'goods_id', 'status'], $where);
//            $goodsList = mActivityRegisterGoods::getList($where, ['register_id', 'goods_id', 'status']);

            $shopRegisterIds = array_column($goodsList, 'register_id');
            $registerIds = array_diff($registerIds, $shopRegisterIds);
            foreach ($registerIds as $registerId) {
                $registerInfo = isset($registerInfoList[$registerId]) ? $registerInfoList[$registerId] : [];
                if ($registerInfo) {
                    $result['activity_register_info'][] = sprintf('#%s# 已启动报名，报名截止时间 %s， 点击左侧【促销 --- 平台活动】查看详细信息', $registerInfo['title'], $registerInfo['stop_time']);
                }
            }
            //活动选中商品通知
            if ($goodsList) {
                $goodsIds = [];
                foreach ($goodsList as $row) {
                    if ($row['status'] == mSelectGoodsLog::STATUS_NORMAL) {
                        array_push($goodsIds, $row['goods_id']);
                    }
                }
                if ($goodsIds) {
                    $goodsIds = array_unique($goodsIds);
                    $specialList = sShopSpecial::getRegisterSpecialInfos($goodsIds);
                    if ($specialList) {
                        $goodsIds = array_keys($specialList);
                        $goods = sGoods::Goods($goodsIds, sGoods::FIELDS_GROUP_BASE);
                        if ($goods) {
                            $goodsIds = array_keys($goods);
                            $activityRegisterGoods = [];
                            foreach ($specialList as $goodsId => $row) {
                                foreach ($row as $specialId => $specialInfo) {
                                    if ($specialInfo && in_array($goodsId, $goodsIds)) {
                                        $activityRegisterGoods[$specialId][$goodsId] = [
                                            'title' => $goods[$goodsId]['title'],
                                            'start_time' => $specialInfo['start_time'],
                                            'special_title' => $specialInfo['special_title'],
                                        ];
                                    }
                                }
                            }

                            foreach ($activityRegisterGoods as $specialId => $items) {
                                foreach ($items as $goodsId => $item) {
                                    if (count($items) > 1) {
                                        $result['activity_register_goods'][] = "商品「" . $item['title'] . "」等多件商品, 已入选 " . $item['start_time'] . "开始的活动「" . $item['special_title'] . "」,快去看看吧";
                                    } else {
                                        $result['activity_register_goods'][] = "商品「" . $item['title'] . "」已入选 " . $item['start_time'] . "开始的活动「" . $item['special_title'] . "」,快去看看吧";
                                    }
                                    break;
                                }
                            }

                        }
                    }
                }
            }
        }
        return $result;
    }

    /**
     * 检查商品是否已入到活动表
     * **/
    public static function admCheckGoods($specialId, $goodsId)
    {
        $list = mShopSpecialGoods::getList(['special_id' => $specialId, 'goods_id' => $goodsId, 'status' => mShopSpecialGoods::STATUS_PASSED]);
        if ($list) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 后台导出活动报名的商品
     * @param $registerId
     * @param $param
     * @param $page
     * @param $pageSize
     * @param $type
     * @throws \Exception
     */
    public static function admDownList($registerId, $param, $page, $pageSize, $type)
    {

        $where = self::buildWhere($registerId, $param);
        $registerInfo = mActivityRegisterInfo::getRegisterInfoByRegisterId($registerId);
        $goodsList = mActivityRegisterGoods::getRegisterGoods($where, ['register_id', 'discount_level', 'discount_type', 'goods_id', 'sku_id', 'is_pick_up', 'discount_degree', 'actual_price']);
        $goodsIds = array_unique(array_column($goodsList, 'goods_id'));
        $skuIds = array_unique(array_column($goodsList, 'sku_id'));
        if (!is_null($page)) $goodsIds = array_slice($goodsIds, ($page - 1) * $pageSize, $pageSize);

        // type == 1    为商品级别导出 type == 0 为sku级别导出
        if ($type == 1) {
            self::downListByGoods($registerId, $param, $page, $pageSize, $registerInfo, $type);
        } else {
            self::downListBySku($registerId, $goodsIds, $skuIds, $goodsList, $registerInfo, $type);
        }
    }

    /**
     * 导出商品相关信息
     * @param $registerId
     * @param $param
     * @param $page
     * @param $pageSize
     * @param $type
     * @param $registerInfo
     */
    public static function downListByGoods($registerId, $param, $page, $pageSize, $registerInfo, $type)
    {
        $downList = [];
        $list = self::admGetRegisterGoods($registerId, $param, $page, $pageSize);
        foreach ($list['list']['goods_info'] as $info) {
            $downList[] = [
                'uid' => $info['uid'],
                'shop_name' => $info['shop_name'],
                'goods_id' => $info['goods_id'],
                'title' => $info['title'],
                'category_name' => $info['category_name'],
                'second_category_name' => $info['second_category_name'],
                'min_price' => $info['min_price'],
                'max_price' => $info['max_price'],
                'activity_min_price' => $info['activity_min_price'],
                'activity_max_price' => $info['activity_max_price'],
                'activity_min_discount' => $info['activity_min_discount'],
                'activity_max_discount' => $info['activity_max_discount'],
                'stock' => $info['stock'],
                'cart_count' => isset($info['cart_count']) ? $info['cart_count'] : 0,
                'fav_count' => isset($info['fav_count']) ? $info['fav_count'] : 0,
                'sell_total' => $info['sell_total'],
                'first_online_time' => $info['first_online_time'],
                'recent_special_title' => isset($info['recent_special_title']) ? $info['recent_special_title'] : '',
                'special_title_list' => isset($info['special_title_list']) ? implode(' ', $info['special_title_list']) : '',
            ];
        }
        admRegisterExcel::downList($registerInfo['title'], $downList, $type);
    }

    /**
     * 导出sku相关信息
     * @param $registerId
     * @param $goodsIds
     * @param $skuIds
     * @param $goodsList
     * @param $type
     * @param $registerInfo
     */
    public static function downListBySku($registerId, $goodsIds, $skuIds, $goodsList, $registerInfo, $type)
    {
        $goodsInfo = sGoods::goods($goodsIds, sGoods::FIELDS_GROUP_BASE); // 商品的基础信息
        $goodsInfo = self::getShopInfoByGoodsInfo($goodsInfo); // 获取商家信息
        $goodsInfo = self::getFavTotalByGoodIds($goodsIds, $goodsInfo); // 商品的收藏信息
        $goodsInfo = self::getCateGoryName($goodsInfo); // 获取分类名称
        $goodsInfo = self::getRecentActivity($goodsIds, $goodsInfo); // 最近一场活动
        $goodsInfo = self::getSelectedActivityTitle($registerId, $goodsInfo); // 获取选中的活动标题
        $skuInfo = sSku::sku($goodsIds, sSku::FIELDS_GROUP_ALL);

        // sku维度的加购总数 信息
        {
            $cartNum = mCart::admGetCartNumBySKUIds($skuIds);
            $cartVNum = mCartv::admGetCartNumBySKUIds($skuIds);

            $cartSum = [];
            foreach ($cartNum as $cart) {
                $cartSum[$cart['sku_id']] = $cart['count'];
            }

            foreach ($cartVNum as $vCart) {
                if (isset($cartSum[$vCart['sku_id']])) {
                    $cartSum[$vCart['sku_id']] = $vCart['count'] + $cartSum[$vCart['sku_id']];
                } else {
                    $cartSum[$vCart['sku_id']] = $vCart['count'];
                }
            }
        }

        // 价格相关
        {
            $skuPriceList = [];
            // 取出实际价格
            foreach ($goodsList as $info) {
                $skuPriceList[$info['goods_id']][$info['sku_id']] = $info['actual_price'];
            }

            // 计算每个sku的折扣
            foreach ($skuPriceList as $goodsId => $skuPrice) {
                foreach ($skuPrice as $skuId => $price) {
                    if (isset($skuInfo[$goodsId]['sku_info']) && $skuInfo[$goodsId]['sku_info']) {
                        foreach ($skuInfo[$goodsId]['sku_info'] as $key => $sku) {
                            if ($sku['sku_id'] == $skuId) {
                                $skuInfo[$goodsId]['sku_info'][$key]['actual_price'] = $price;
                                $skuInfo[$goodsId]['sku_info'][$key]['dis_count'] = round($price / $sku['ori_price'], 2) * 10;
                            }
                        }
                    }
                }
            }
        }

        // sku 下单数量
        {
            $skuSellTotal = [];
            $sellTotal = mOrderGoods::admGetCartNumBySkuIds($skuIds);
            foreach ($sellTotal as $total) {
                $skuSellTotal[$total['sku_id']] = $total['count'];
            }
        }

        $list = [];
        foreach ($goodsIds as $goodsId) {
            foreach ($skuInfo[$goodsId]['sku_info'] as $info) {
                $list[] = [
                    'uid' => $goodsInfo[$goodsId]['uid'],
                    'shop_name' => $goodsInfo[$goodsId]['shop_name'],
                    'goods_id' => $goodsId,
                    'goods_name' => $goodsInfo[$goodsId]['title'],
                    'sku_id' => $info['sku_id'],
                    'sku_desc' => $info['sku_desc'],
                    'ori_price' => $info['ori_price'],
                    'actual_price' => $info['actual_price'],
                    'dis_count' => $info['dis_count'],
                    'stock' => $info['stock'],
                    'cart_count' => isset($cartSum[$info['sku_id']]) ? $cartSum[$info['sku_id']] : 0, // 从购物车里面取数据
                    'fav_count' => isset($goodsInfo[$goodsId]['fav_count']) ? $goodsInfo[$goodsId]['fav_count'] : 0,
                    'sell_total' => isset($skuSellTotal[$info['sku_id']]) ? $skuSellTotal[$info['sku_id']] : 0, // 从order_goods里面取数据
                    'category_name' => $goodsInfo[$goodsId]['category_name'],
                    'second_category_name' => $goodsInfo[$goodsId]['second_category_name'],
                    'first_online_time' => $goodsInfo[$goodsId]['first_online_time'],
                    'recent_special_title' => isset($goodsInfo[$goodsId]['recent_special_title']) ? $goodsInfo[$goodsId]['recent_special_title'] : '',
                    'special_title_list' => isset($goodsInfo[$goodsId]['special_title_list']) ? implode(' ', $goodsInfo[$goodsId]['special_title_list']) : '',
                ];
            }
        }

        admRegisterExcel::downList($registerInfo['title'], $list, $type);
    }

    /**
     * 处理折扣 活动价
     * @param $goodsIds
     * @param $goodsList
     * @param $goodsInfo
     * @return mixed
     */
    public static function formatPrice($goodsIds, $goodsList, $goodsInfo)
    {
        $actualPrice = $disCount = [];
        $skuInfo = sSku::Sku($goodsIds, sSku::FIELDS_GROUP_SKU_INFO);

        foreach ($goodsList as $info) {
            if (isset($skuInfo[$info['goods_id']])) {
                foreach ($skuInfo[$info['goods_id']] as $item) {
                    if ($info['sku_id'] == $item['sku_id']) {
                        $disCount[$info['goods_id']][] = round($info['actual_price'] / $item['ori_price'], 2) * 10;
                        $actualPrice[$info['goods_id']][] = $info['actual_price'];
                    }
                }
            }
        }

        foreach ($goodsInfo as $goodsId => $value) {
            $minDisCount = isset($disCount[$goodsId]) ? min($disCount[$goodsId]) : 0;
            $maxDisCount = isset($disCount[$goodsId]) ? max($disCount[$goodsId]) : 0;
            $minActualPrice = isset($actualPrice[$goodsId]) ? min($actualPrice[$goodsId]) : 0;
            $maxActualPrice = isset($actualPrice[$goodsId]) ? max($actualPrice[$goodsId]) : 0;
            $goodsInfo[$goodsId]['activity_min_discount'] = $minDisCount;
            $goodsInfo[$goodsId]['activity_max_discount'] = $maxDisCount;
            $goodsInfo[$goodsId]['activity_min_price'] = $minActualPrice;
            $goodsInfo[$goodsId]['activity_max_price'] = $maxActualPrice;
        }

        return $goodsInfo;
    }

    /**
     * 获取商家信息
     * @param $goodsInfo
     * @return mixed
     */
    private static function getShopInfoByGoodsInfo($goodsInfo)
    {
        $shopIds = array_column($goodsInfo, 'uid');
        $shopInfo = sShopInfo::getShopInfoList($shopIds);
        foreach ($goodsInfo as $info) {
            if (isset($shopInfo[$info['uid']])) {
                $goodsInfo[$info['goods_id']]['shop_name'] = $shopInfo[$info['uid']]['name'];
            }
        }
        return $goodsInfo;
    }

    /**
     * 获取加购总数
     * @param $goodsIds
     * @param $goodsInfo
     * @return mixed
     */
    private static function getCartTotalByGoodsIds($goodsIds, $goodsInfo)
    {
        $cartNum = mCart::admGetCartNumByGoodsIds($goodsIds);
        $cartVNum = mCartv::admGetCartNumByGoodsIds($goodsIds);
        $cartNumSum = array_merge($cartNum, $cartVNum);

        foreach ($goodsInfo as $goods) {
            $num = 0;
            foreach ($cartNumSum as $info) {
                if ($goods['goods_id'] == $info['goods_id']) {
                    $num += $info['count'];
                }
            }
            $goodsInfo[$goods['goods_id']]['cart_count'] = $num;
        }

        return $goodsInfo;
    }

    /**
     * 获取收藏的总数
     * @param $goodsIds
     * @param $goodsInfo
     * @return mixed
     */
    private static function getFavTotalByGoodIds($goodsIds, $goodsInfo)
    {
        $total = mShopFavorite::getFavCountByGoodIds($goodsIds, 'obj_id');
        foreach ($goodsInfo as $goods) {
            foreach ($total as $goodsId => $goodsCount) {
                if ($goods['goods_id'] == $goodsId) {
                    $goodsInfo[$goodsId]['fav_count'] = count($total[$goodsId]) ?: 0;
                }
            }
        }

        return $goodsInfo;
    }

    /**
     * 获取分类名称
     * @param $goodsInfo
     * @return mixed
     */
    private static function getCateGoryName($goodsInfo)
    {
        $categoryIds = array_merge(array_column($goodsInfo, 'category_id'), array_column($goodsInfo, 'second_category_id'));
        $categoryInfo = array_column(mCategory::getCategoryList($categoryIds, null), null, 'id');

        foreach ($goodsInfo as $info) {
            $goodsInfo[$info['goods_id']]['category_name'] = $categoryInfo[$info['category_id']]['cate_name'];
            $goodsInfo[$info['goods_id']]['second_category_name'] = $categoryInfo[$info['second_category_id']]['cate_name'];
        }

        return $goodsInfo;
    }

    /**
     * 拼装where条件
     * @param $registerId
     * @param array $param
     * @return array
     */
    private static function buildWhere($registerId, $param = [])
    {
        $greyListShopIds = [];
        if ($param['grey_list'] == 1) {
            $greyList = mShopGreyList::select('shop_id', ['status' => mShopGreyList::STATUS_NORMAL]);
            if ($greyList) {
                $greyListShopIds = $greyList;
            }
        }
        $where = [];
        // 商家信息搜索条件
        if (isset($param['field1']) && $param['field1']) {
            if ($param['keyword1'] && $param['field1'] == 1) {
                $where['shop_id'] = $param['keyword1'];
            } else if ($param['keyword1'] && $param['field1'] = 2) {
                $results = AdmUserSearch::getUserIdsByFilter(['user_type' => [Member::AUTH_USER_BRAND], 'nick' => $param['keyword1']], 1);
                $where['shop_id'] = $results['rows'];
            }
        }

        // 如果选中了排除灰名单商家的话需要进行过滤.,如果shop_id的条件存在的话,则过滤掉灰名单. 如果shop_id不存在的话 将条件置为!=shop_id
        if (isset($where['shop_id']) && $where['shop_id'] && $greyListShopIds) {
            $where['shop_id'] = array_diff($where['shop_id'], $greyListShopIds);
        } else if ($greyListShopIds) {
            $where['shop_id[!]'] = $greyListShopIds;
        }

        // 商品信息搜索条件
        if (isset($param['field2']) && $param['field2']) {
            if ($param['keyword2'] && $param['field2'] == 1) {
                $where['goods_id'] = $param['keyword2'];
            } else if ($param['keyword2'] && $param['field2'] = 2) {
                // 来源是商城后台 需要传递的条件是
                // ['title' => $param['keyword2']]
                $results = SearchGoods::searchEntrance(['title' => $param['keyword2'], 'source' => esGoods::SOURCE_SHOP_ADMIN], esGoods::SCENES_SHOP_ADMIN_TITLE, 0, 1, '*');
//                $results = SearchGoods::searchByCommon(['AND' => ['title[~]' => $param['keyword2']]]);
                if ($results['total']) {
                    $where['goods_id'] = $results['rows'];
                }

                // todo 搜索切换es待删除
//                $results = Goods::searchByConditions(['title' => $param['keyword2']]);
//                $where['goods_id'] = $results['rows'];
            }
        }

        // 查询出最近入选的活动包含的商品id
        if (isset($param['special_id']) && $param['special_id']) {
            $selectLogWhere = [
                'shop_id' => isset($where['shop_id']) ? $where['shop_id'] : 0,
                'goods_id' => isset($where['goods_id']) ? $where['goods_id'] : 0,
            ];
            $selectLogWhere = array_filter($selectLogWhere);
            $selectLogWhere = array_merge([
                'activity_id' => $param['special_id'],
                'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE,
                'status' => mSelectGoodsLog::STATUS_NORMAL,
            ], $selectLogWhere);
            $where['goods_id'] = array_unique(mSelectGoodsLog::select('goods_id', array_filter($selectLogWhere)));
        }

        // 因为 [查询入选的活动] 条件 与 [只看未选中] 条件冲突 (查询入选的活动一定是选中的) 所以分开处理

        if (!isset($where['goods_id'])) {
            if (isset($param['status']) && $param['status'] == 1) {
                // 如果只查看未选中的话, 需要把已选中的id查出来过滤
                $filterGoodsIds = mSelectGoodsLog::select('goods_id', [
                    'register_id' => $registerId,
                    'status' => mSelectGoodsLog::STATUS_NORMAL,
                    'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
                ]);
                if ($filterGoodsIds) {
                    $where['goods_id[!]'] = array_unique($filterGoodsIds);
                }
            }
        }

        $where['status'] = mActivityRegisterGoods::STATUS_NORMAL;

        $where['register_id'] = $registerId;

        return $where;
    }

    private static function isExist($registerId, $shopId)
    {
        $registerInfo = mActivityRegisterInfo::getRegisterInfo($registerId);
        $registerIds = mActivityRegisterShop::getRegsterIdsByShopId($shopId);
        if ($registerInfo['all_shop'] ||
            ($registerInfo['status'] != mActivityRegisterInfo::STATUS_DELETE &&
                in_array($registerId, $registerIds))) {
            return true;
        }

        return false;
    }

    /**
     * 创建log表数据
     * @param $registerId
     * @param $activityId
     * @param $goodsIds
     * @param $goodsInfo
     * @param $adminId
     * @param $goodsList
     * @param $specialInfo
     * @return array
     */
    private static function buildSelectGoodsLogData($registerId, $activityId, $goodsIds, $goodsInfo, $adminId, $goodsList, $specialInfo)
    {
        $logList = [];
        foreach ($goodsIds as $goodsId) {
            foreach ($goodsList as $info) {
                if ($info['goods_id'] == $goodsId)
                    $logList[] = [
                        'register_id' => $registerId,
                        'activity_id' => $activityId,
                        'type' => ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE,
                        'shop_id' => $goodsInfo[$goodsId]['uid'],
                        'goods_id' => $goodsId,
                        'sku_id' => $info['sku_id'],
                        'actual_price' => $info['actual_price'],
                        'start_time' => $specialInfo['start_time'],
                        'end_time' => $specialInfo['end_time'],
                        'addtime' => date('Y-m-d H:i:s'),
                        'edittime' => date('Y-m-d H:i:s'),
                        'admin_id' => $adminId,
                        'status' => mSelectGoodsLog::STATUS_NORMAL,
                    ];
            }
        }
        return $logList;
    }

    /**
     * 构造all_activity_sku表所需数据
     * @param $activityId
     * @param $goodsIds
     * @param $specialInfo
     * @param $goodsInfo
     * @param $goodsList
     * @return array
     */
    private static function buildActivitySku($activityId, $goodsIds, $specialInfo, $goodsInfo, $goodsList)
    {
        $activitySkuInfo = [];
        foreach ($goodsList as $info) {
            foreach ($goodsIds as $goodsId) {
                if ($info['goods_id'] == $goodsId) {
                    $activitySkuInfo[] = [
                        'activity_id' => $activityId,
                        'type' => ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE,
                        'shop_id' => $goodsInfo[$goodsId]['uid'],
                        'goods_id' => $goodsId,
                        'sku_id' => $info['sku_id'],
                        'is_activity_stock' => mAllActivitySku::NOT_USE_ACTIVITY_STOCK,
                        'activity_price' => $info['actual_price'],
                        'start_time' => $specialInfo['start_time'],
                        'end_time' => $specialInfo['end_time'],
                        'real_start_time' => $specialInfo['start_time'],
                        'real_end_time' => $specialInfo['end_time'],
                        'status' => mAllActivitySku::STATUS_NORMAL,
                    ];
                }
            }
        }
        return $activitySkuInfo;
    }

    /**
     * 构造all_activity_goods表所需数据
     * @param $activityId
     * @param $goodsIds
     * @param $specialInfo
     * @param $goodsInfo
     * @return array
     */
    private static function buildActivityGoods($activityId, $goodsIds, $specialInfo, $goodsInfo)
    {
        $activityGoodsInfo = [];
        foreach ($goodsIds as $goodsId) {
            $activityGoodsInfo[$goodsId] = [
                'goods_id' => $goodsId,
                'shop_id' => $goodsInfo[$goodsId]['uid'],
                'activity_id' => $activityId,
                'type' => ActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE,
                'status' => mAllActivityGoods::STATUS_NORMAL,
                'start_time' => $specialInfo['start_time'],
                'end_time' => $specialInfo['end_time'],
                'real_start_time' => $specialInfo['start_time'],
                'real_end_time' => $specialInfo['end_time'],
            ];
        }

        return $activityGoodsInfo;
    }

    /**
     * 获取活动关联的报名商品
     * @param $specialId
     * @return array
     */
    public static function getSelectedSpecialGoods($specialId)
    {
        $goodsIds = mSelectGoodsLog::select('goods_id', [
            'activity_id' => $specialId,
            'status' => mSelectGoodsLog::STATUS_NORMAL,
            'type' => AllActivityInfo::ACTIVITY_TYPE_WEEK_PURCHASE
        ]);
        return array_unique($goodsIds);
    }

    /**
     * 获取商品的活动信息
     * @param $goodsIds
     * @return array
     */
    public static function getRegisterInfos($goodsIds)
    {
        $registerInfos = mActivityRegisterGoods::getList([
            'goods_id' => $goodsIds,
            'status' => [mActivityRegisterGoods::STATUS_NORMAL]
        ]);
        $registerIds = array_column($registerInfos, 'register_id');
        $registerInfosGrpByGids = [];
        if ($registerIds) {
            $registers = mActivityRegisterInfo::getInfosByRegisterIds($registerIds);
            foreach ($registerInfos as $registerInfo) {
                if (!isset($registerInfosGrpByGids[$registerInfo['goods_id']][$registerInfo['register_id']]) && isset($registers[$registerInfo['register_id']])) {
                    $registerInfosGrpByGids[$registerInfo['goods_id']][$registerInfo['register_id']] = $registers[$registerInfo['register_id']];
                }
            }
        }
        return $registerInfosGrpByGids;

    }

}
